import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class TestDemo8 {
    public static int sum = 0;
    public static void main(String[] args) throws InterruptedException {
/*
        Semaphore semaphore = new Semaphore(2); //构造方法的参数表示信号量
        semaphore.acquire(); //获取一个可用资源
        System.out.println("P 操作");
        semaphore.acquire();
        System.out.println("P 操作");
        semaphore.acquire(); //信号量已经为 0 了，再 acquire 就会阻塞
        System.out.println("P 操作");
        semaphore.release(); //释放一个可用资源
        System.out.println("V 操作");
*/
        CountDownLatch Latch = new CountDownLatch(5); //要等待 5 个线程
        for(int i = 0;i < 5;i++) {
            int n = i;
            Thread t = new Thread(()->{
                int time = (new Random().nextInt(5)+1) * 1000;
                System.out.println("线程 " + n + " 开始下载");
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程 " + n + " 下载完成");
                Latch.countDown(); //告知 CountDownLatch 该线程执行完毕
            });
            t.start();
        }
        Latch.await(); //调用 await 来等待所有任务结束
        System.out.println("所有任务执行完成");
    }
}
